/*    file: AacPackager.cpp
 *    desc:
 * 
 * created: 2014-07-21 15:24:43
 *  author: zhengchuanjiang
 * company: 
 */

#include "stdafx.h"
#include "AacPackager.h"
#include "RtpHeader.h"
#include "AacHelper.h"

#define AU_HEADER_SIZE  4


AacPackager::AacPackager():
    m_file(),
	m_profile(),
	m_freq(),
	m_channels()
{
	m_buffer.ensure(av::AacHelper::ADTS_HEADER_SIZE);
}

AacPackager::~AacPackager()
{
    close();
}

bool AacPackager::open(int profile, int freq, int channels, const char* filename)
{
	m_profile = profile;
	m_freq = freq;
	m_channels = channels;


    fopen_s(&m_file, filename, "wb");
    return (m_file != NULL);
}

bool AacPackager::isOpen()
{
    return (m_file != NULL);
}

void AacPackager::close()
{
    if (m_file)
    {
        fclose(m_file);
        m_file = NULL;
    }
}


static unsigned char s_startCode[] = { 0, 0, 0, 1};

void AacPackager::write(BYTE* ptr, UINT16 size)
{
    if (!isOpen())
    {
        return;
    }

	RTP_FIXED_HEADER* rtpHeader = (RTP_FIXED_HEADER*)ptr;

	if (size <= sizeof(RTP_FIXED_HEADER))
	{
		return;
	}
	   

    BYTE* pPayload = ptr + sizeof(RTP_FIXED_HEADER);
    size_t  length = size - sizeof(RTP_FIXED_HEADER);

	if (length <= sizeof(AU_HEADER_SIZE))
	{
		return;
	}
    
	BYTE* data = pPayload + sizeof(AU_HEADER_SIZE);
	length -= sizeof(AU_HEADER_SIZE);

    if (rtpHeader->extension)
    {
        RTP_EXT_HEADER* extHeader = (RTP_EXT_HEADER*)data;
        int extLength = ntohs(extHeader->length);

        data += 4 + extLength * 4;
        length -= 4 + extLength * 4;

        if (length <= 0)
        {
            return;
        }
    }

	uint8_t* buffer = m_buffer.data();
	size_t maxSize = m_buffer.capacity();
	av::AacHelper::makeAdtsHeader(m_profile, m_freq, m_channels, length + av::AacHelper::ADTS_HEADER_SIZE, buffer, maxSize);

	fwrite(buffer, 1, av::AacHelper::ADTS_HEADER_SIZE, m_file);

    fwrite(data, 1, length, m_file);
	fflush(m_file);

    m_buffer.clear();
    
}
